<template>
  <div id="questionsView">
    <div class="exam-header">
      <!-- 左侧: 考试信息 -->
      <a-card class="exam-card" title="考试名称"> {{ form.examName }} </a-card>

      <!-- 右侧: 倒计时 -->
      <a-countdown
        :key="countdownKey"
        class="exam-countdown"
        title="剩余时间"
        :value="form.endTime"
        :now="now"
      />
    </div>
    <div>
      <a-button type="primary" @click="toRank(record)"> 排名 </a-button>
    </div>
    <a-divider size="0" />
    <a-table
      :ref="tableRef"
      :columns="columns"
      :data="dataList"
      :pagination="{
        showTotal: true,
        pageSize: searchParams.pageSize,
        current: searchParams.current,
        total,
      }"
      @page-change="onPageChange"
    >
      <template #acceptedRate="{ record }">
        {{
          record.submitNum
            ? `${((record.acceptedNum / record.submitNum) * 100).toFixed(
                2
              )}% (${record.acceptedNum}/${record.submitNum})`
            : "0% (0/0)"
        }}
      </template>

      <template #optional="{ record }">
        <a-space>
          <a-button
            type="primary"
            @click="toQuestionPage(record)"
            :disabled="!isExamEnd(record.endTime)"
          >
            做题
          </a-button>
        </a-space>
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from "vue";
import {
  ExamControllerService,
  ExamQuestionControllerService,
  ExamQuestionVO,
  Question,
} from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRoute, useRouter } from "vue-router";
import { format } from "date-fns";
const router = useRouter();

const tableRef = ref();
const dataList = ref([]);
const total = ref(0);

let form = ref({
  examName: "",
  examDesc: "",
  startTime: format(new Date(), "yyyy-MM-dd'T'HH:mm:ssxxx"), // 生成符合格式的时间
  endTime: format(new Date(), "yyyy-MM-dd'T'HH:mm:ssxxx"),
  examPassword: "",
  isPublic: 0,
});

const columns = [
  {
    title: "题目名称",
    dataIndex: "title",
  },
  {
    title: "通过率",
    slotName: "acceptedRate",
  },
  {
    slotName: "optional",
  },
];

const searchParams = ref({
  examId: -1,
  pageSize: 10,
  current: 1,
});
const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};
const route = useRoute();
const loadData = async () => {
  const id = route.query.id;
  if (!id) return;
  const res = await ExamControllerService.getExamVoByIdUsingGet(id as any);
  if (res.code === 0) {
    form.value = res.data as any;
    searchParams.value.examId = res.data?.id as any;
    await loadQuestionRes(); // 确保数据加载完成
  } else {
    message.error("加载失败，" + res.message);
  }
};

const loadQuestionRes = async () => {
  const res =
    await ExamQuestionControllerService.listMyExamQuestionVoByPageUsingPost(
      searchParams.value
    );
  if (res.code === 0) {
    const examQuestion = res.data.records as ExamQuestionVO[];
    dataList.value = examQuestion.map((item) => item.questionVO);
    // 过滤掉 null 和 undefined
    total.value = res.data.total;
  } else {
    message.error("加载失败，" + res.message);
  }
};

// 获取考试的开始和结束时间
const endTime = ref(new Date(form.value.endTime).getTime());

// 定时器变量
let timer: number | null = null;

// 当前时间，每秒更新
const now = ref(Date.now());

// 计算倒计时的 `key`，让 `a-countdown` 重新渲染
const countdownKey = computed(() => `countdown-${now.value}`);

const isExamEnd = (endTime: string) => {
  if (!endTime) return false;
  return new Date().getTime() >= new Date(endTime).getTime();
};

onMounted(() => {
  timer = setInterval(() => {
    now.value = Date.now(); // 触发 Vue 重新渲染
    if (now.value >= endTime.value && timer !== null) {
      clearInterval(timer);
      timer = null;
    }
  }, 1000);
});

onUnmounted(() => {
  if (timer !== null) {
    clearInterval(timer);
    timer = null;
  }
});

/**
 * 监听 searchParams 变量，改变时触发页面的重新加载
 */
/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
});

/**
 * 跳转到做题页面
 * @param question
 */
const toQuestionPage = (question: Question) => {
  router.push({
    path: "/view/exam_question",
    query: {
      examId: route.query.id,
      questionId: question.id,
    },
  });
};

const toRank = () => {
  router.push({
    path: "/view/examination/rank",
    query: {
      examId: route.query.id,
    },
  });
};
</script>

<style scoped>
.exam-header {
  display: flex;
  justify-content: space-between; /* 左右对齐 */
  align-items: center; /* 垂直居中 */
  width: 100%;
  padding: 10px 20px;
  background: #f5f5f5;
  border-radius: 10px;
}

.exam-card {
  width: 360px;
  flex-shrink: 0; /* 防止缩小 */
}

.exam-countdown {
  font-size: 18px;
}
</style>
